package com.wetask.admin.service;

import java.io.File;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.wetask.dao.BannerDao;
import com.wetask.domain.model.Banner;
import com.wetask.domain.model.PagingInfo;
import com.wetask.domain.model.SearchResult;
import com.wetask.model.vo.BannerVO;
import com.wetask.utils.DataHelper;

@Service
public class ManageBannerService {
	
	@Autowired
	private BannerDao bannerDao;
	
	@Value("${upload.banners.url.server}")
	public String URL_ROOT_FOLDER_UPLOAD_BANNER;

	@Value("${upload.banners.url.project}")
	public String URL_PROJECT_UPLOAD_BANNER;
	
	public SearchResult<Banner> getBanner(PagingInfo pagingInfo, String keyword){
		return bannerDao.getBanner(pagingInfo, keyword);
	}
	
	@SuppressWarnings("deprecation")
	public boolean uploadBanner(Model model, BannerVO bannerVO, HttpServletRequest request){
		//get root in project
		//String urlRootProject = request.getRealPath(DataHelper.FolderImageFileUploadInProject.EBOOK_IMAGE.getCode()) ;
		String urlRootProject = request.getRealPath(URL_PROJECT_UPLOAD_BANNER) ;
		
		//upload file
		CommonsMultipartFile bannerFileUpload = bannerVO.getFileBannerUpload();
		//String rootUrl = DataHelper.UrlRootFolderUpload.URL_ROOT_FOLDER_UPLOAD_EBOOK.getCode();
		String rootUrl = URL_ROOT_FOLDER_UPLOAD_BANNER;
		Date dateCurrentImage = new Date();
		long dateCurrentTimeImage = dateCurrentImage.getTime();
		bannerVO.setCreateDate(dateCurrentImage);
		
		//url image file
		String urlFileBannerFull = rootUrl;
		String urlFileBannerFullInProject = urlRootProject;
		
		//upload image file
		boolean hasErrorUploadBanner = true;
		if (bannerFileUpload == null || bannerFileUpload.getSize() <= 0) {
			hasErrorUploadBanner = true;
			model.addAttribute("errorUploadBanner", DataHelper.UploadFileStatus.UPLOAD_EMPTY.getCode());
		} else {
			String fileName = bannerFileUpload.getOriginalFilename();
			if(fileName.indexOf(".") < 1){
				hasErrorUploadBanner = true;
				model.addAttribute("errorUploadBanner", DataHelper.UploadFileStatus.UPLOAD_EMPTY.getCode());
			}else{
				String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
				String urlFileBanner = "/banner_" + dateCurrentTimeImage +"/banner_" + dateCurrentTimeImage + "." + fileType;
				urlFileBannerFull = rootUrl + urlFileBanner;
				urlFileBannerFullInProject = urlFileBannerFullInProject + urlFileBanner;
				bannerVO.setNameFile(bannerFileUpload.getOriginalFilename());
				bannerVO.setUrlFile(urlFileBanner);
				
				String fileTypeImageList = DataHelper.ImageFile.IMAGE_FILE_TYPE.getCode();
				String maxSizeImageStr = DataHelper.ImageFile.IMAGE_FILE_MAX_LENGTH.getCode();
				long maxSizeImage = Long.parseLong(maxSizeImageStr);
				
				String resultUploadFileBanner = uploadSingleFile(bannerFileUpload, urlFileBannerFull, maxSizeImage, fileTypeImageList);
				
				if (DataHelper.ResultUpload.RESULT_UPLOAD_SUCCESS.getCode().equals(resultUploadFileBanner)) {
					
					//upload to folder project
					//uploadSingleFile(imageFileUpload, urlFileImageFullInProject, maxSizeImage, fileTypeImageList);
					copyFile(urlFileBannerFull, urlFileBannerFullInProject);
					
					hasErrorUploadBanner = false;
					model.addAttribute("errorUploadBanner", DataHelper.UploadFileStatus.UPLOAD_SUCCESS.getCode());
				} else if(DataHelper.ResultUpload.RESULT_UPLOAD_ERROR.getCode().equals(resultUploadFileBanner)){
					model.addAttribute("errorUploadBanner", DataHelper.UploadFileStatus.UPLOAD_FILE_ERROR.getCode());
				} else if(DataHelper.ResultUpload.RESULT_UPLOAD_INCORRECT.getCode().equals(resultUploadFileBanner)){
					model.addAttribute("errorUploadBanner", DataHelper.UploadFileStatus.UPLOAD_FILE_FAILURE_FORMAT.getCode());
				} else if(DataHelper.ResultUpload.RESULT_UPLOAD_LIMIT.getCode().equals(resultUploadFileBanner)){
					model.addAttribute("errorUploadBanner", DataHelper.UploadFileStatus.UPLOAD_FILE_LIMIT.getCode());
				}
			
			}
		}
		
		model.addAttribute("hasErrorUploadBanner", hasErrorUploadBanner);
		if(!hasErrorUploadBanner){
			return true;
		}else{
			return false;
		}
	}
	
	public String uploadSingleFile(CommonsMultipartFile filea, String fullPathFileName, long maxSize,String fileTypeList){
		boolean testType = false;
		if(fileTypeList != null){
			
			//check file type
			String [] fileTypeArray = fileTypeList.split(",");
			String filename = null;
			String fileTypeCurrent = null;
			try{
				filename = filea.getOriginalFilename();
				fileTypeCurrent = filename.substring(filename.lastIndexOf(".")+1);
			}catch (Exception e) {
				e.printStackTrace();
				return DataHelper.ResultUpload.RESULT_UPLOAD_INCORRECT.getCode();
			}
			
			if(fileTypeArray.length > 0){
				for(int i = 0; i < fileTypeArray.length; i++){
					if(fileTypeArray[i].equalsIgnoreCase(fileTypeCurrent)){
						testType = true;
					};
				}
			}
		}else{
			testType = true;
		}
		if(testType){
			if (filea.getSize() > 0 && (filea.getSize() <= maxSize || maxSize == 0)) {
				try {
					File file = new File(fullPathFileName);
					file.mkdirs();
					filea.transferTo(file);
				} catch (Exception e) {
					e.printStackTrace();
					return DataHelper.ResultUpload.RESULT_UPLOAD_ERROR.getCode();
				}
				return DataHelper.ResultUpload.RESULT_UPLOAD_SUCCESS.getCode();
			} else {
				return DataHelper.ResultUpload.RESULT_UPLOAD_LIMIT.getCode();
			}
		}else{
			return DataHelper.ResultUpload.RESULT_UPLOAD_INCORRECT.getCode();
		}
	}
	
	public void copyFile(String fromFile, String toFile){
		try{
			File input = new File(fromFile);
			File output = new File(toFile);
			//output.mkdir();
			FileUtils.copyFile(input, output); 
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	//save
	public void saveBanner(BannerVO bannerVO){
		bannerDao.saveBanner(bannerVO);
	}
	
	//get delete
	public void deleteBanner(int id){
		bannerDao.deleteBanner(id);
	}
	
	//get detail
	public Banner getBannerDetail(int id){
		return bannerDao.getBannerDetail(id);
	}
}
